<template>
  <div v-loading="loading">
    <el-form ref="form" :model="form" :rules="rules" label-width="120px" class="dataForm">
      <el-row>
        <el-col :span="12">
          <el-form-item :label="$t('项目名称')" prop="dealId">
            <main-body-select v-model="form.dealId" :placeholder="$t('项目名称')" parameters="deal" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('投资主体')" prop="investId">
            <el-select v-model="form.investId" :placeholder="$t('投资主体')" @change="changeInvest">
              <el-option v-for="item in dealInvestmentList" :key="item.id" :value="item.investorId" :label="item.shortName" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('事项类型')" prop="itemType">
            <dict-select v-model="form.itemType" :placeholder="$t('事项类型')" dictionary="ic_item_type" @change="changeInvest" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item :label="$t('申请标题')" prop="actTitle">
            <el-input v-model="form.actTitle" :placeholder="$t('流程标题')" show-word-limit maxlength="100" />
          </el-form-item>
        </el-col>
        <el-col v-if="!loading" :span="24">
          <el-form-item :label="$t('申请内容')" prop="applyContent">
            <EditorTxt ref="editorTxt" v-model="form.applyContent" :placeholder="$t('申请内容')" :height="350" />
          </el-form-item>
        </el-col>
      </el-row>
      <!--文件-->
      <FileTable :list.sync="form.fileList" data-type="deal_ic_meeting" :btn-show="!otherBtnHide" />
    </el-form>
    <div slot="footer" class="dialog-footer" style="text-align: right;">
      <!--保存 取消按钮-->
      <FormBtn ref="formBtn" :bus-data="form" has-permi="deal:icMeeting" :btn-hide="btnHide" />
    </div>
  </div>
</template>

<script>
    import { saveDealIcMeeting, getDealIcMeeting } from '@/api/deal/icMeeting/dealIcMeeting'
    import MainBodySelect from '@/components/MainBodySelect/index.vue'
    import { listDealInvestment } from '@/api/deal/investment/dealInvestment'
    import { getFundName } from '@/api/fund/fundBase'
    import { getDealName } from '@/api/base/deal/dealBase'
    import EditorTxt from '@/components/Tinymce'
    export default {
        components: { EditorTxt, MainBodySelect },
        data() {
            return {
                // 表单参数
                form: {},
                // 遮罩层
                loading: false,
                otherBtnHide: false,
                // 表单校验
                rules: {
                  investId: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
                  itemType: [{ required: true, message: this.$t('必填信息'), trigger: 'change' }],
                  actTitle: [{ required: true, message: this.$t('必填信息'), trigger: 'change' }],
                  applyContent: [
                    { required: true, message: this.$t('必填信息'), trigger: 'change' },
                    { validator: this.validateContent, trigger: 'change' }
                  ]
                },
              btnHide: false,
              itemTypeOptions: [],
              dealInvestmentList: []
            }
        },
        created() {
          if (this.$route.query.id) {
            this.getDealInvestmentList()
          }
          this.getDicts('ic_item_type').then(res => {
            this.itemTypeOptions = res.data
          })
          this.$bus.$emit('async_done')
        },
        methods: {
            // 初始化数据
            init(data) {
                this.loading = true
                if (data != null && data.id !== undefined) {
                    getDealIcMeeting(data.id).then(response => {
                        this.form = response.data

                        if (!this.$route.query.id) {
                          this.getDealInvestmentList()
                        }

                        this.loading = false
                    }).catch(() => {
                      this.loading = false
                    })
                } else {
                    this.reset()

                    this.$nextTick(() => {
                      if (this.dealInvestmentList && this.dealInvestmentList.length > 0) {
                        this.form.investId = this.dealInvestmentList[0].investorId
                        this.changeInvest()
                      }
                    })

                    this.loading = false
                }
            },
          validateContent(rule, value, cb) {
            var num = this.form.applyContent.length
            try {
              // const text = this.$refs.editorTxt.$el.innerText
              // var temp = text.split('\n')
              // temp = temp[temp.length - 1]
              // num = Number(temp.replace('字', ''))
              num = this.$refs.editorTxt.wordcount

              if (isNaN(Number(num))) {
                num = this.form.applyContent.length
              }
            } catch (e) {
              console.error(e)
              num = this.form.applyContent.length
            }

            if (num > 2000) {
              cb(new Error(this.$t('字数不能超过2000')))
            } else {
              cb()
            }
          },
            getDealInvestmentList() {
              listDealInvestment({ dealId: this.$route.query.id || this.form.dealId }).then(res => {
                this.dealInvestmentList = res.rows
                if (res.rows && res.rows.length) {
                  this.form.investId = this.form.investId || res.rows[0].investorId
                  this.changeInvest()
                }
              })
            },
            async changeInvest() {
              let name = ''
              if (this.form.investId) {
                name = await getFundName(this.form.investId)
                if (!name) {
                  const dealInvestment = this.dealInvestmentList.find(item => item.investorId === this.form.investId)
                  name = dealInvestment && dealInvestment.investorName || ''
                }
              }
              const dealName = await getDealName(this.form.dealId)
              this.form.actTitle = name + '-' + dealName + '-' + (this.form.itemType ? this.selectDictLabel(this.itemTypeOptions, this.form.itemType) : '')
            },
            // 表单重置
            reset() {
                this.form = {
                    id: undefined,
                    dealId: this.$route.query.id,
                    itemType: undefined,
                    investId: undefined,
                    actTitle: undefined,
                    applyContent: undefined,
                    remark: undefined,
                    delFlag: undefined,
                    createBy: undefined,
                    createTime: undefined,
                    updateBy: undefined,
                    updateTime: undefined,
                  fileList: []
                }
                this.resetForm('form')
            },
            // 取消按钮
            cancel() {
                this.$parent.$parent.formOpen = false
                this.$parent.$parent.reset()
            },
            // 关闭form页面
            closeForm() {
                // 关闭form页面遮罩层
                this.loading = false
                // 关闭form页面
                if (this.$parent.$parent.formOpen !== undefined) {
                  this.$parent.$parent.formOpen = false
                }
                // 刷新list页面
                if (this.$parent.$parent.getList !== undefined) {
                  this.$parent.$parent.getList()
                }
            },
          // 启动流程
          startProcess(data) {
            this.loading = false
            // 启动流程时候传入的参数
            const processData = {}
            // 待办标题
            processData.title = this.form.actTitle
            // 业务表名
            processData.dataTable = 'deal_ic_meeting'
            // 业务ID
            processData.dataId = data.id
            // 业务表单地址(待办页面需要打开的页面)
            processData.formPath = '@/views/deal/icMeeting/dealIcMeetingForm'
            // 菜单标识(根据菜单标识判断的走哪个流程)
            processData.menuKey = 'ic_meeting'
            // processKey 流程配置
            this.startProcessByMenu(processData, () => {
              this.form.actStatus = 'D'
              this.msgSuccess(this.$t('数据保存成功,流程启动成功'))
              this.closeForm()
            })
          },
            /** 提交按钮 */
            submitForm(type) {
                console.log(type, '11')
                return new Promise((resolve) => {
                  this.$refs['form'].validate(valid => {
                    if (valid) {
                      this.loading = true
                      this.form.saveType = type
                      saveDealIcMeeting(this.form).then(response => {
                        if (type === 'process') {
                          this.startProcess(response.data)
                        } else {
                          this.msgSuccess(this.$t('保存成功'))
                          this.closeForm()
                        }
                        console.log(response.data.id)
                        resolve(response.data.id)
                        this.loading = false
                      })
                    } else {
                      this.locationError(document)
                    }
                  })
                })
           }
        }
    }
</script>
